from flask import jsonify, make_response, request, g
from flask_restful import Resource
from sqlalchemy import func

from apps.model.serializeModel import model_to_list, model_to_dict
from apps.settingApi.api.users.model import usersModel
from apps.settingApi.switchCase.casePrimaryKey import caseGetPrimaryKeyData
from apps.settingApi.switchCase.serializeParameter import getArgsData, serializeParData, serializeGetFilter, \
    pageResultData

from apps.settingApi.switchCase.settingCurd import getPk
from apps.settingApi.api.lessees.model import lesseesModel,lesseesFunsModel
from apps.settingApi.api.funs.model import funsModel
from apps.settingApi.utils import getDataTime
from comm.dateTime import nowData
from comm.sqlalchemyConfig import db
from comm.decorator import login_required, decorator_dealer

lesseesViewModel = lesseesModel
usersViewModel = usersModel
lesseesFunsViewModel = lesseesFunsModel
funsViewModel = funsModel

class lesseesValidListView(Resource):

    def get(self):
        dataList = []
        # 格式化获取当前时间
        formatted_datetime = getDataTime()
        modelData = db.session.query(lesseesViewModel.id,lesseesViewModel.name).filter(lesseesViewModel.end_time>=formatted_datetime).all()
        for itm in modelData:
            dataList.append({
                "id":itm.id,
                "name":itm.name
            })
        return make_response(jsonify({'msg': 'ok', 'result': dataList}), 200)

class lesseesListView(Resource):
    @login_required()
    @decorator_dealer()
    def get(self):
        # 获取所有的参数
        serializeFilterList,args = serializeGetFilter(lesseesViewModel)
        valid = args.get("valid", '1')
        # 1查询全部、2查询未过期的3、查询过期的
        if valid in ('1','2','3'):
            if valid=='2':
                serializeFilterList.append(lesseesViewModel.end_time > getDataTime())
            if valid == '3':
                serializeFilterList.append(lesseesViewModel.end_time <= getDataTime())
        modelDataObj = lesseesViewModel.query.filter(*serializeFilterList).order_by(lesseesViewModel.id.desc()).paginate(page=args['page'], per_page=args['pageSize'], error_out=False)
        objData = pageResultData(modelDataObj)
        result = model_to_list(modelDataObj, [])
        objData["data"] = result  # 分页数据
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)


    @login_required()
    @decorator_dealer()
    def post(self):
        # 获取参数
        args, err = getArgsData()
        if err != None:
            return make_response(jsonify({'msg': err, }), 202)
        # 设置id
        max_id = db.session.query(func.max(lesseesViewModel.id)).scalar()
        id_z =  "{:06d}".format(int(max_id)+1)
        args['create_user'] = g.user_id
        args['type']=2
        args['id']=id_z
        # 序列化跟校验参数
        addData,err = serializeParData(model=lesseesViewModel,argsData = args)
        if err!=None:
            return make_response(jsonify({'msg': err}), 202)
        # 判断名称是否重复
        exit_z = db.session.query(lesseesViewModel).filter_by(name=args['name']).first()
        if exit_z!=None:
            return make_response(jsonify({'msg': '名称重复'}), 202)
        result = db.session.query(lesseesViewModel).with_for_update().filter_by(id=id_z).first()
        # 如果数据不存在，则添加新数据
        if result != None:
            db.session.commit()
            return make_response(jsonify({'msg': '抢先操作重新提交试试'}), 202)
        try:
            add = lesseesViewModel(**addData)
            db.session.add(add)
            db.session.commit()
            db.session.flush()
            objData = model_to_dict(add, [])
        except Exception as e:
            return make_response(jsonify({'msg': '新增失败' + repr(e)}), 202)
        # 创建账号
        addUser = {}
        addUser['create_user'] = g.user_id
        addUser['type'] = 1
        addUser['id'] = caseGetPrimaryKeyData()
        addUser['lessees_id'] = id_z
        addUser['code'] = id_z
        addUser['username'] = id_z
        addUser['password'] = id_z
        addUser['start_time'] = nowData()
        addUser['end_time'] = nowData(year=1)
        print(addUser)
        add = usersViewModel(**addUser)
        db.session.add(add)
        db.session.commit()
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)

class lesseesPkView(Resource):
    @login_required()
    @decorator_dealer()
    def get(self, pk):
        objData, err = getPk(lesseesViewModel, pk)
        if err != None:
            return make_response(jsonify({'msg': err}), 202)
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)

    @login_required()
    @decorator_dealer()
    def put(self, pk):
        args,err = getArgsData()
        if err!=None:
            return make_response(jsonify({'msg': err, }), 202)
        addData,err = serializeParData(model=lesseesViewModel,argsData = args)
        if err!=None:
            return make_response(jsonify({'msg': err,}), 202)
        # 判断名称是否重复
        exit_z = db.session.query(lesseesViewModel).filter(lesseesViewModel.id!=pk,lesseesViewModel.name==args['name']).first()
        if exit_z!=None:
            return make_response(jsonify({'msg': '名称重复', }), 202)
        addr = lesseesViewModel.query.filter(lesseesViewModel.id==pk).with_for_update().first()
        for itm in addData.keys():
            setattr(addr, itm, addData[itm])
        db.session.commit()
        # 获取更新的数据
        update = lesseesViewModel.query.filter(lesseesViewModel.id == pk).first()
        if update is None:
            return None, '获取更新后的数据失败'
        objData = model_to_dict(update, [])
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)

    @login_required()
    @decorator_dealer()
    def delete(self, pk):
        # 查询数据
        result = lesseesViewModel.query.filter(lesseesViewModel.id == pk).first()
        if result == None:
            return make_response(jsonify({'msg': '数据不存在'}), 200)
        # 获取影藏不需要显示的数据
        resultData = model_to_dict(result, [])
        try:
            deletedata = db.session.query(lesseesViewModel).filter(lesseesViewModel.id == pk).with_for_update().first()
            deletedata.end_time = getDataTime(strftime='%Y-%m-%d 00:00:00')
            db.session.commit()
        except Exception as e:
            return make_response(jsonify({'msg': '删除失败' + repr(e)}), 200)

        return make_response(jsonify({'msg': '成功', 'result': resultData}), 200)


class lesseesFunsListView(Resource):
    @login_required()
    @decorator_dealer()
    def get(self):
        args = request.args
        lessees_id = args.get('lessees_id',None)
        if lessees_id is None or lessees_id=='':
            return make_response(jsonify({'msg': '参数不能为空'}), 202)
        # 获取所有的功能
        funsList = funsViewModel.getAll()
        # 获取租户的功能
        lesseesFuns = lesseesFunsViewModel.query.filter(lesseesFunsViewModel.lessees_id==lessees_id,funsViewModel.code==lesseesFunsModel.funs_code,funsViewModel.status==1,func.coalesce(funsViewModel.parent_code,'')=='').all()
        lesseesFunslist = list(map(lambda x:x.funs_code,lesseesFuns))

        data = {
            'checkedKeys':lesseesFunslist,
            'data':funsList,
        }
        return make_response(jsonify({'msg': '成功', 'result': data}), 200)

    @login_required()
    @decorator_dealer()
    def post(self):
        # 获取参数
        args, err = getArgsData()
        if err != None:
            return make_response(jsonify({'msg': err, }), 202)
        lessees_id = args.get('lessees_id', None)
        if lessees_id is None or lessees_id == '':
            return make_response(jsonify({'msg': '参数不能为空'}), 202)
        checkedKeys = args.get('checkedKeys', None)
        if checkedKeys is None or checkedKeys == '':
            return make_response(jsonify({'msg': '参数不能为空'}), 202)
        db.session.query(lesseesFunsViewModel).filter(lesseesFunsViewModel.lessees_id == lessees_id).delete()
        addList = []
        for itm in checkedKeys:
            itm_z = {}
            itm_z['id'] = caseGetPrimaryKeyData()
            itm_z['funs_code'] = itm
            itm_z['lessees_id'] = lessees_id
            addList.append(lesseesFunsViewModel(**itm_z))
        if len(addList)>0:
            db.session.add_all(addList)
        db.session.commit()

        return make_response(jsonify({'msg': '成功', 'result': []}), 200)
